/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "app.h"
#include "math.h"

#include <string.h>
#include "ad7175_ctrl.h"
#include "da5541_ctrl.h"
#include "display_ctrl.h"
//#include "Parameter.h"
#include "eeprom_ctrl.h"



/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void DA_Enable_Control(uint8_t Enable);
void Vol_Cur_Mode_Control(void);
void Sys_Res_Control(void);
void Mag_Sys_Control(uint8_t Key_Num);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

#define RXBUFFERSIZE  256     	//最大接收字节数  串口接收
uint8_t RxBuffer[RXBUFFERSIZE];	//接收数据
uint8_t aRxBuffer;							//接收中断缓冲
uint8_t Uart1_Rx_Cnt = 0;				//接收缓冲计数


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_SPI1_Init();
  MX_SPI2_Init();
  MX_USART1_UART_Init();
  MX_I2C1_Init();
  MX_TIM2_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
	HAL_UART_Receive_IT(&huart1, (uint8_t *)&aRxBuffer, 1);
	HAL_TIM_Base_Start_IT(&htim2);//定时器2开始运行

	DA5541_Init();//DA初始化
	Power_Amp_Init();//功放IO控制初始化
	Mag_Flux_Init();//磁通档位初始化
	AD7175_INIT();//AD初始化
	Parameter_Init();//参数初始化
  APP_Init();       //  2025/3/5hjy：初始化业务模块
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
      APP_LCMD_ProcessHandler();      //  2025/3/14miaozi：上位机服务
			if(AD_Delay_Time_0==0)			//每50ms读取一次AD值
			{
				AD_Delay_Time_0 = 1;			//标志位置1 避免单片机反复进入

				AD7175_AIN1AIN2_VALUE();	//同时读取AD 通道0和通道1

				AD_Sampl_I_Value = (float)((AD_AIN0_value-Basic_Value)/(3.9*0.025*PGA204_value*PGA207_value))*Kad_value;//AD与电流转换关系
				AD_Sampl_Mag_Value = 0.4*((AD_AIN1_value-2.5)/2.5)*H_Solenoid_correct_Km;//AD与磁通转换关系

				Display_FloatNum(AD_Mag_VALUE_ADD,AD_Sampl_Mag_Value);//在串口屏上显示当前采样电流大小
				Display_FloatNum(AD_Cur_VALUE_ADD,AD_Sampl_I_Value); //在串口屏上显示当前采样磁通大小
			}
			if(Uart1Receive_Flag==1)
			{
				switch(Display_Key_Num)
				{

					case BIG_MODE_KEYNUM:	//电流档位调节
					case SMALL_MODE_KEYNUM:
						Current_Control(Display_Key_Num);
						break;

					case VOLTAGE_CURRENT_KEYNUM://电压电流源切换
						Vol_Cur_Mode_Control();
						break;

					case DA_ENABLE_KEYNUM://DA使能控制
						if(++DA_Enable==2) DA_Enable=0;
						DA_Enable_Control(DA_Enable);
						break;

					case MAG_FLUX_KEYNUM://磁通档位调节
						Mag_Flux_Control();
						break;

					case SYS_RES_KEYNUM://系统复位控制
						Sys_Res_Control();
						break;

					case MAG_RES_KEYNUM://磁通计复位 清零 漂移抑制 漂移调整
					case MAG_RESTRAIN_KEYNUM:
					case MAG_ADJUST_KEYNUM:
					case MAG_CLEAR_KEYNUM:
						Mag_Sys_Control(Display_Key_Num);
						break;

					case SYS_CODE_KEYNUM://系统密码设置
						if(++Sys_Inside_Flag==3) Sys_Inside_Flag=0;//连续点击3次 手动跳转到密码界面
						if(Sys_Inside_Flag==0)
						{
							Skip_to_Page(CODE_PAGE_KEYNUM);
							Page_Now = CODE_PAGE_KEYNUM;//记录当前界面编号
						}
						break;

					case SAMPL_AD_KEYNUM://AD相对采样 电流
						Sampl_AD_Zero();
						break;

					case CLEAR_AD_KEYNUM://AD相对采样清零
						Clear_AD_Zero();
						break;

					case BALLISTIC_METHOD_KEYNUM://冲击法触发按键
						Ballistic_Method_Detect();
						break;

					default: break;
				}
				//在DA使能状态下 当输入变量地址为DA对应数据时
				if((DA_Enable==1)&&(Display_Data_ADD==DA_VALUE_ADD))
				{
					if(Display_Num<=0xFFFF)
					{
						DA5541_Generate_CS0((float)Display_Num/10000);
						Display_FloatNum(DA_VALUE_ADD,(float)Display_Num/10000);
					}
					else
					{
						DA5541_Generate_CS0(0.0-(float)(0xFFFFFFFF-Display_Num+1)/10000);//需将Display_Num装换为浮点数进行使用
						Display_FloatNum(DA_VALUE_ADD,(0.0-(float)(0xFFFFFFFF-Display_Num+1)/10000));
					}
				}
				//40以下键码为页面跳转返回值 此处将页面记录方便后续使用
				if((Display_Key_Num<0x0040)&&(Display_Key_Num!=0))
				{
					Page_Now=Display_Key_Num;
				}
				//当处于密码输入界面进入密码判断
				if(Page_Now==CODE_PAGE_KEYNUM)
				{
					if(Display_Num==888888) PassWord_Flag = 1;//密码正确
					if((PassWord_Flag==1)&&(Display_Key_Num==0x0102)) //0x0102为该界面下确定按键的返回值
					{
						Skip_to_Page(SYS_INSIDE_KEYNUM);//跳转至系统内部界面
						Page_Now = SYS_INSIDE_KEYNUM;
						PassWord_Flag = 0;
					}
				}
				//在电流修正系数界面下 手动输入电流修正系数
				if((Display_Data_ADD>=CUR_COR_FACTOR_1_ADD)&&(Display_Data_ADD<=CUR_COR_FACTOR_13_ADD))
				{
					Correct_Factor_Input((Display_Data_ADD-CUR_COR_FACTOR_1_ADD)/4,Display_Num);
				}
				//参数清零 防止下次进入是判断错误
				Uart1Receive_Flag = 0;
				Display_Key_Num = 0;
				Display_Data_ADD = 0;
				Display_Num = 0;
			}
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }

  /** Enables the Clock Security System
  */
  HAL_RCC_EnableCSS();
}

/* USER CODE BEGIN 4 */

void DA_Enable_Control(uint8_t Enable)
{
	uint8_t Aaa[]="使能状态";
	uint8_t Bbb[]="失能状态";
	DA_Switch(Enable);
	if(Enable==0)//DA失能
	{
		DA5541_Generate_CS0(0);//同时使DA输出为0
		Display_FloatNum(DA_VALUE_ADD,0);
		Display_Write_Variable(DA_STATE_ADD,Bbb,sizeof(Bbb));
	}
	else Display_Write_Variable(DA_STATE_ADD,Aaa,sizeof(Aaa));
}

void Vol_Cur_Mode_Control(void)
{
	static uint8_t Mode_value=0;
	uint8_t Aaa[]="电流源";
	uint8_t Bbb[]="电压源";
	if(++Mode_value==2)
	{
		Mode_value=0;
		Display_Write_Variable(VOL_CUR_STATE_ADD,Aaa,sizeof(Aaa));
	}else Display_Write_Variable(VOL_CUR_STATE_ADD,Bbb,sizeof(Bbb));

	Voltage_Current_Sourch_Switch(Mode_value);
}

void Sys_Res_Control(void)
{
	uint8_t Aaa[]="系统空闲";
	Error_Flag = 0;//系统复位将报错标志位清零
	SYS_Protect_Enable(0);
	Sys_Res_Enable(1);
	Display_Write_Variable(SYS_STATE_ADD,Aaa,sizeof(Aaa));
}

void Mag_Sys_Control(uint8_t Key_Num)
{
	uint8_t Aaa[]="系统已复位  ";
	uint8_t Bbb[]="开启漂移抑制";
	uint8_t Ccc[]="开启漂移调整";
	uint8_t Ddd[]="磁通计清零  ";

	switch(Key_Num)
	{
		case MAG_RES_KEYNUM:
			Display_Write_Variable(MAG_STATE_ADD,Aaa,sizeof(Aaa));
			Mag_Clear_Enable(0);
			Drift_Adjust_Enable(0);
			Drift_Restrain_Enable(0);
			Drift_Restrain_flag=0;
		  Drift_Adjust_flag=0;
			Mag_Clear_flag=0;
			break;
		case MAG_RESTRAIN_KEYNUM:
			Drift_Restrain_Enable(1);
			Display_Write_Variable(MAG_STATE_ADD,Bbb,sizeof(Bbb));
			Drift_Restrain_flag=1;
			break;
		case MAG_ADJUST_KEYNUM:
			Drift_Adjust_Enable(1);
			Display_Write_Variable(MAG_STATE_ADD,Ccc,sizeof(Ccc));
			Drift_Adjust_flag=1;
			break;
		case MAG_CLEAR_KEYNUM:
			Mag_Clear_Enable(1);
			Display_Write_Variable(MAG_STATE_ADD,Ddd,sizeof(Ddd));
			Mag_Clear_flag=1;
			break;
	}
}


void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(huart);
  /* NOTE: This function Should not be modified, when the callback is needed,
           the HAL_UART_TxCpltCallback could be implemented in the user file
  */

	if(Uart1_Rx_Cnt >= 50)  //溢出判断
	{
		Uart1_Rx_Cnt = 0;
		memset(RxBuffer,0x00,sizeof(RxBuffer));
	}
	else if(Uart1Receive_Flag==0)
	{
		RxBuffer[Uart1_Rx_Cnt++] = aRxBuffer;
		if((RxBuffer[0]==0x5A)&&(RxBuffer[1]==0xA5))
		{
			if((Uart1_Rx_Cnt>3)&&(Uart1_Rx_Cnt==RxBuffer[2]+3))
			{//接收数据成功
				Uart1_Rx_Cnt = 0;
				Uart1Receive_Flag = 1;
				if((RxBuffer[3]==0x83)&&(RxBuffer[6]==0x01))//按键键码
				{
					Display_Key_Num = (uint16_t)(RxBuffer[7]<<8)|(RxBuffer[8]);
				}
				if((RxBuffer[3]==0x83)&&(RxBuffer[6]==0x02))//数据变量
				{
					Display_Num = (uint32_t)(RxBuffer[7]<<24)|(RxBuffer[8]<<16)|(RxBuffer[9]<<8)|(RxBuffer[10]);
					Display_Data_ADD = (uint16_t)(RxBuffer[4]<<8)|(RxBuffer[5]);
				}
				memset(RxBuffer,0x00,sizeof(RxBuffer));//数组清零
			}
		}
	}
	HAL_UART_Receive_IT(&huart1, (uint8_t *)&aRxBuffer, 1);   //再开启接收中断

  // 2025/3/14miaozi:上面代码看不懂，别管了
  if (huart->Instance == USART2)
  {
    APP_LCMD_ControlSerialRxHandler(USART2RxData);
  //        // 重新启用接收中断，以便继续接收数据
    HAL_UART_Receive_IT(&huart2,(uint8_t *)&USART2RxData, 1);
  }

}

//1ms定时中断，用于分配时间段
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    static unsigned char ledState = 0;
    if(htim == (&htim2))//此处时间段划分按需求进行 近似操作系统写法
    {
			if(++AD_Delay_Time_0==50) AD_Delay_Time_0=0;				//AD检测速率 正常运行下可较低速度检测50-1 = 49ms
			if(++AD_Delay_Time_1==4) AD_Delay_Time_1=0;					//冲击法下要匹配DA速率AD_Delay_Time_1 -1 = 3ms采样一个点
			if(++DA_OUT_Delay_1==2) DA_OUT_Delay_1=0;						//边沿DA输出速率 DA_OUT_Delay_1 - 1 = 1ms输出一个边沿点
			if(++DA_OUT_Delay_2==31) DA_OUT_Delay_2=0;					//顶峰DA输出速率 DA_OUT_Delay_2 - 1 = 30ms输出一个峰值点
    }
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)//引脚外部中断 检测报警信息 并进行报警处理
{
  if(GPIO_Pin==GPIO_PIN_11)
  {
		uint8_t Error_String[]="过压警报";
		Error_Flag = 1;
		SYS_Protect_Enable(1);
		Display_Write_Variable(SYS_STATE_ADD,Error_String,sizeof(Error_String));
    __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_11);
  }
	else if(GPIO_Pin==GPIO_PIN_13)
  {
		uint8_t Error_String[]="过流警报";
		Error_Flag = 2;
		SYS_Protect_Enable(1);
		Display_Write_Variable(SYS_STATE_ADD,Error_String,sizeof(Error_String));
    __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_13);
  }
	else if(GPIO_Pin==GPIO_PIN_14)
  {
		uint8_t Error_String[]="过热警报";
		Error_Flag = 3;
		SYS_Protect_Enable(1);
		Display_Write_Variable(SYS_STATE_ADD,Error_String,sizeof(Error_String));
    __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_14);
  }
	else if(GPIO_Pin==GPIO_PIN_12)
  {
		uint8_t Error_String[]="开始检测";
		Display_Write_Variable(SYS_STATE_ADD,Error_String,sizeof(Error_String));
    __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_12);
  }
	Display_BzTime(100);//蜂鸣器鸣叫1s
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
